--
-- Author: mengjie0718@163.com
-- Date: 2014-12-23 11:20:32
--
require("script.config")
local updater = require("script.update.updater")
local sharedDirector         = cc.Director:getInstance()
local kResolutionNoBorder = 1
-- check device screen size
local glview = sharedDirector:getOpenGLView()
local size = glview:getFrameSize()
local display = {}
display.sizeInPixels = {width = size.width, height = size.height}

local w = display.sizeInPixels.width
local h = display.sizeInPixels.height
local scale, scaleX, scaleY
if type(CONFIG_SCREEN_AUTOSCALE_CALLBACK) == "function" then
    scaleX, scaleY = CONFIG_SCREEN_AUTOSCALE_CALLBACK(w, h)
else
    scaleX, scaleY = w / CONFIG_SCREEN_WIDTH, h / CONFIG_SCREEN_HEIGHT
end
if CONFIG_SCREEN_AUTOSCALE == "FIXED_WIDTH" then
    scale = scaleX
    CONFIG_SCREEN_HEIGHT = h / scale
elseif CONFIG_SCREEN_AUTOSCALE == "FIXED_HEIGHT" then
    scale = scaleY
    CONFIG_SCREEN_WIDTH = w / scale
else
    scale = 1.0
end


sharedDirector:setDisplayStats(DEBUG_FPS)

sharedDirector:setAnimationInterval(1.0/30)
glview:setDesignResolutionSize(CONFIG_SCREEN_WIDTH, CONFIG_SCREEN_HEIGHT, kResolutionNoBorder)

local winSize = sharedDirector:getWinSize()
display.contentScaleFactor = scale
display.size               = {width = winSize.width, height = winSize.height}
display.width              = display.size.width
display.height             = display.size.height
display.cx                 = display.width / 2
display.cy                 = display.height / 2
display.c_left             = -display.width / 2
display.c_right            = display.width / 2
display.c_top              = display.height / 2
display.c_bottom           = -display.height / 2
display.left               = 0
display.right              = display.width
display.top                = display.height
display.bottom             = 0
display.widthInPixels      = display.sizeInPixels.width
display.heightInPixels     = display.sizeInPixels.height

print("# display in updateScene start")
print(string.format("# us.CONFIG_SCREEN_AUTOSCALE      = %s", CONFIG_SCREEN_AUTOSCALE))
print(string.format("# us.CONFIG_SCREEN_WIDTH          = %0.2f", CONFIG_SCREEN_WIDTH))
print(string.format("# us.CONFIG_SCREEN_HEIGHT         = %0.2f", CONFIG_SCREEN_HEIGHT))
print(string.format("# us.display.widthInPixels        = %0.2f", display.widthInPixels))
print(string.format("# us.display.heightInPixels       = %0.2f", display.heightInPixels))
print(string.format("# us.display.contentScaleFactor   = %0.2f", display.contentScaleFactor))
print(string.format("# us.display.width                = %0.2f", display.width))
print(string.format("# us.display.height               = %0.2f", display.height))
print(string.format("# us.display.cx                   = %0.2f", display.cx))
print(string.format("# us.display.cy                   = %0.2f", display.cy))
print(string.format("# us.display.left                 = %0.2f", display.left))
print(string.format("# us.display.right                = %0.2f", display.right))
print(string.format("# us.display.top                  = %0.2f", display.top))
print(string.format("# us.display.bottom               = %0.2f", display.bottom))
print(string.format("# us.display.c_left               = %0.2f", display.c_left))
print(string.format("# us.display.c_right              = %0.2f", display.c_right))
print(string.format("# us.display.c_top                = %0.2f", display.c_top))
print(string.format("# us.display.c_bottom             = %0.2f", display.c_bottom))
print("# display in updateScene done")
local function CCPoint(x,y)
    return {x=x,y=y}
end
--Size
local function CCSzie( _width,_height )
    return { width = _width, height = _height }
end

--Rect
local function CCRect(_x,_y,_width,_height)
    return { x = _x, y = _y, width = _width, height = _height }
end
display.ANCHOR_POINTS = {
    CCPoint(0.5, 0.5),  -- CENTER
    CCPoint(0, 1),      -- TOP_LEFT
    CCPoint(0.5, 1),    -- TOP_CENTER
    CCPoint(1, 1),      -- TOP_RIGHT
    CCPoint(0, 0.5),    -- CENTER_LEFT
    CCPoint(1, 0.5),    -- CENTER_RIGHT
    CCPoint(0, 0),      -- BOTTOM_LEFT
    CCPoint(1, 0),      -- BOTTOM_RIGHT
    CCPoint(0.5, 0),    -- BOTTOM_CENTER
}

display.CENTER        = 1
display.LEFT_TOP      = 2; display.TOP_LEFT      = 2
display.CENTER_TOP    = 3; display.TOP_CENTER    = 3
display.RIGHT_TOP     = 4; display.TOP_RIGHT     = 4
display.CENTER_LEFT   = 5; display.LEFT_CENTER   = 5
display.CENTER_RIGHT  = 6; display.RIGHT_CENTER  = 6
display.BOTTOM_LEFT   = 7; display.LEFT_BOTTOM   = 7
display.BOTTOM_RIGHT  = 8; display.RIGHT_BOTTOM  = 8
display.BOTTOM_CENTER = 9; display.CENTER_BOTTOM = 9

function display.align(target, anchorPoint, x, y)
    target:setAnchorPoint(display.ANCHOR_POINTS[anchorPoint])
    if x and y then target:setPosition(x, y) end
end

local us = cc.Scene:create()
us.name = "updateScene"

local localResInfo = nil
local function ccc3(r,g,b)
    return {r=r,g=g,b=g}
end 
function us._addUI()
    -- Get the newest resinfo in ures.
   
    local __label = cc.LabelTTF:create("Loading...", "Arial", 24)
    __label:setColor(ccc3(255, 255, 255))
    us._label = __label

    display.align(__label, display.CENTER, display.cx, 93)
    us:addChild(__label, 10)
   
    
end
function us.setProgress(percent)
    percent = tonumber(percent)*100
    if us.barbg==nil then
        
        local scale9sp = ccui.Scale9Sprite or cc.Scale9Sprite
        

        local barbg =  ccui.LoadingBar:create("image/ui/login/jdt-5.png",0)
        barbg:setScale9Enabled(true)
        barbg:setCapInsets({x=1,y=0,width=86,height=19})
        barbg:setContentSize(CCSize(display.width-180,19))
        us:addChild(barbg)
        barbg:setPosition(display.cx, 93)
        us.barbg = barbg
       
        -- us._label:setVisible(false)
        barbg = cc.Sprite:create("image/ui/login/jdt-1.png")
        display.align(barbg, display.CENTER, display.cx, 100)
        us:addChild(barbg)
        barbg = scale9sp:create({x=58,y=20,width=50,height=10},"image/ui/login/jdt-2.png")
        barbg:setContentSize(CCSize(display.width-100,61))
        display.align(barbg, display.CENTER, display.cx, 93)
        us:addChild(barbg)
        tipsLang = {
        "正在加载，请耐心等待！",
        }
        local getTip=function()
            return tipsLang[math.random(1,#tipsLang)]
        end
        local tips = cc.LabelTTF:create(getTip(), "Arial", 22)
        tips:setColor(ccc3(0xf9, 0xe6, 0xcb))
        display.align(tips, display.CENTER, display.cx, 50)
        us:addChild(tips, 10)
       
        tips:runAction(cc.RepeatForever:create(cc.Sequence:create(cc.DelayTime:create(5), cc.CallFunc:create(function()
                tips:setString(getTip())
        end))))
        barbg = cc.Sprite:create("image/ui/login/dldtbg.png")
        barbg:setScaleX((display.width)/barbg:getContentSize().width)
        display.align(barbg, display.CENTER, display.cx, barbg:getContentSize().height/2)
        us:addChild(barbg)
    end
    us.barbg:setPercent(percent)
end
function us._getres(path)
    if not localResInfo then
        localResInfo = updater.getResCopy()
    end
    for key, value in pairs(localResInfo.oth) do
        print("us._getres:", key, value)
        local pathInIndex = string.find(key, path)
        if pathInIndex and pathInIndex >= 1 then
            print("us._getres getvalue:", path)
            res[path] = value
            return value
        end
    end
    return path
end

function us._sceneHandler(event)
    
    if event == "enter" then
        print(string.format("updateScene \"%s:onEnter()\"", us.name))
        us.onEnter()
    elseif event == "cleanup" then
        print(string.format("updateScene \"%s:onCleanup()\"", us.name))
        us.onCleanup()
    elseif event == "exit" then
        print(string.format("updateScene \"%s:onExit()\"", us.name))
        us.onExit()

        if DEBUG_MEM then
            print("----------------------------------------")
            print(string.format("LUA VM MEMORY USED: %0.2f KB", collectgarbage("count")))
            CCTextureCache:sharedTextureCache():dumpCachedTextureInfo()
            print("----------------------------------------")
        end
    end
end

function us._updateHandler(event, value)
    updater.state = event
    if event == "success" then
        updater.stateValue = value
        updater.updateFinalResInfo()
        us.performWithDelay(function()
            if us._succHandler then
                us._succHandler()
                us._succHandler = nil
            end
        end,1/30)
        
    elseif event == "error" then
        updater.stateValue = value
    elseif event == "progress" then
        local progress = value[1]/value[2]
        if progress>1 then
            progress = 1
        end
        updater.stateValue = string.format("%3.2f%%", progress*100)
        
        us._label:setString(updater.stateValue)
        us.setProgress(progress)
        
    elseif event == "state" then
        updater.stateValue = value
        us._label:setString(updater.stateValue)
        -- us.performWithDelay(function()us._label:setString(updater.stateValue)end,1/30)
    elseif event== "downloadStart" then

    end
    
    
end
function us.performWithDelay(callback, delay)
    -- us:stopAllActions()
    us:runAction(cc.Sequence:create(cc.DelayTime:create(delay),cc.CallFunc:create(callback)))
    return action
end
function us.addListener(handler)
    us._succHandler = handler
    return us
end

function us.onEnter()
print("us.onEnter")
    if not us.playing and ccexp and ccexp.VideoPlayer then
        us.playing = true
        local VideoPlayerEvent = {
                        PLAYING = 0,
                        PAUSED = 1,
                        STOPPED= 2,
                        COMPLETED =3,
                    }
        us.performWithDelay(function()
                local isplaying = false
                local videoPlayer = ccexp.VideoPlayer:create()
                videoPlayer:setPosition(CCPoint(display.cx, display.cy))
                videoPlayer:setAnchorPoint(CCPoint(0.5, 0.5))
                videoPlayer:setContentSize(CCSzie(display.width, display.height))
                videoPlayer:addEventListener(function(sener, eventType)
                    
                    if eventType == VideoPlayerEvent.PLAYING then
                        print("PLAYING")
                        isplaying = true
                     elseif eventType == VideoPlayerEvent.PAUSED then
                         print("PAUSED")
                         sener:runAction(cc.Sequence:create(cc.DelayTime:create(0.1), cc.CallFunc:create(function()
                            sener:removeFromParent()
                        end)))
                         us.videoPlayer=nil
                         if us.onVideoEnd then
                             us.onVideoEnd()
                         end
                     elseif eventType == VideoPlayerEvent.STOPPED then
                         print("STOPPED")
                         sener:runAction(cc.Sequence:create(cc.DelayTime:create(0.1), cc.CallFunc:create(function()
                            sener:removeFromParent()
                        end)))
                         us.videoPlayer=nil
                         if us.onVideoEnd then
                             us.onVideoEnd()
                         end
                     elseif eventType == VideoPlayerEvent.COMPLETED then
                        print("COMPLETED")
                        sener:runAction(cc.Sequence:create(cc.DelayTime:create(0.1), cc.CallFunc:create(function()
                            sener:removeFromParent()
                        end)))
                        us.videoPlayer = nil
                        if us.onVideoEnd then
                            us.onVideoEnd()
                        end
                    else
                        print(eventType)
                        sener:runAction(cc.Sequence:create(cc.DelayTime:create(0.1), cc.CallFunc:create(function()
                            sener:removeFromParent()
                        end)))
                        us.videoPlayer = nil
                        if us.onVideoEnd then
                            us.onVideoEnd()
                        end
                    end
                end)
                videoPlayer:setKeepAspectRatioEnabled(false)
                videoPlayer:setFullScreenEnabled(true)
                videoPlayer:setFileName("res/open.mp4")
                videoPlayer:play()
                us:addChild(videoPlayer)
                us.videoPlayer = videoPlayer
                videoPlayer:runAction(cc.RepeatForever:create(cc.Sequence:create(cc.DelayTime:create(1), cc.CallFunc:create(function()
                    if not isplaying then
                        videoPlayer:setFileName("res/open.mp4")
                        videoPlayer:play()
                    else
                        videoPlayer:stopAllActions()
                    end
                end))))
        end,0)
    end
    us._addUI()
end

function us.onExit()
    updater.clean()
end

function us.onCleanup()
us:unregisterScriptHandler()
end

us:registerScriptHandler(us._sceneHandler)


return us